//
//  MyFindBuyViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/29.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "MyFindBuyViewController.h"
#import "BottomBar.h"
#import "FindCarTableViewCell.h"
#import "FindCarMode.h"
#import "FindCarResdMode.h"
#import <MJRefresh.h>
#import "Puser.h"
#import "LookForDetailController.h"
#import "NoItemView.h"
#import "UserInfoUpdateResde.h"
#import "PublishQgViewController.h"
@interface MyFindBuyViewController ()<UITableViewDataSource,UITableViewDelegate,FindCarEidtTableCellDelegate,UIAlertViewDelegate,BottomBarBtnClickDelegate,BottombarDataSource>{
    BOOL _isedting;
    BOOL _candelete;
}
@property (nonatomic,strong) BottomBar *bottombar;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataarray;
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) NoItemView *noitem;
@property (nonatomic,strong) FindCarMode *qgmode;
@end

@implementation MyFindBuyViewController
-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}

-(void)buttonclickWith:(FindCarTableViewCell *)cell WithIndex:(NSInteger)index{
    
    NSIndexPath *indexpath=[self.tableView indexPathForCell:cell];
    FindCarMode *mode=self.dataarray[indexpath.row];
    if (index==0) {
        PublishQgViewController *pvc=[PublishQgViewController publish];
        pvc.findmode=mode;
        [self.navigationController pushViewController:pvc animated:YES];
        
    }else{
        self.qgmode=mode;
        [self showalert:1];
        
       
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        return;
        
    }else{
        if (alertView.tag==0) {
            [self deleteqg];
        }else{
            [self deleteqgItem];
        }
        
    }
    
}
-(void)deleteItem:(NSMutableArray *)array{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.labelText=@"正在操作";
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"user_id"]=[self.user.power integerValue]<5?self.user.user_id:self.user.com_id;
    params[@"type"]=[self.user.power integerValue]<5?@"person":@"company";
    if ([self.user.power integerValue]==8) {
        params[@"pid"]=self.user.parent_id;
    }
    params[@"action"]=@"del_buy";
    params[@"buy_id"]=[NSString DataTOjsonString:array];
    
    [PostUitls Post:myfindcarurl parameters:params success:^(id response) {
        UserInfoUpdateResde *resdmode=[UserInfoUpdateResde resdeWithDict:response];
        if ([resdmode.state integerValue]==400) {
            [self.tableView.header beginRefreshing];
            _candelete=NO;
            self.bottombar.btnenable=_candelete;
            self.bottombar.allselected=_candelete;
            self.qgmode=nil;
        }
        hud.labelText=resdmode.msg;
        hud.mode = MBProgressHUDModeText;
        [hud hide:YES afterDelay:1];
    } failure:^(NSError *error) {
        hud.labelText=@"网络错误";
        hud.mode = MBProgressHUDModeText;
        
    }];

}

+(instancetype)Viewcontroller{
    MyFindBuyViewController *find=[[MyFindBuyViewController alloc]init];
    find.hidesBottomBarWhenPushed=YES;
    return find;
}
-(UITableView *)tableView{
    if (_tableView==nil) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, XHScreenwidth, XHScreenheight) style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.backgroundColor=bgGarycolor;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 56, 0);
    self.navigationItem.title=@"我的求购";
    self.tableView.rowHeight=145;
    UINib *nib=[UINib nibWithNibName:NSStringFromClass([FindCarTableViewCell class]) bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"findcar"];
    [self setupRight:NO];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
    if (self.isFromSUS) {
        NSMutableArray *vcarray=[[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
        [vcarray removeObjectAtIndex:self.navigationController.viewControllers.count-2];
        [vcarray removeObjectAtIndex:self.navigationController.viewControllers.count-3];
        self.navigationController.viewControllers = vcarray;
    }

    
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.tableView.header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadmore)];
    // Do any additional setup after loading the view.
    _noitem=[NoItemView viewWithType:MYFINDCARTYPE];
    [self.tableView addSubview:_noitem];

}

-(void)deleteqg{
    NSMutableArray *IDarray=[NSMutableArray array];
    for (FindCarMode *mode in self.dataarray) {
        if (mode.ischecked) {
            [IDarray addObject:mode.ID];
        }
    }
    [self deleteItem:IDarray];
}
-(void)deleteqgItem{
    NSMutableArray *IDarray=[NSMutableArray array];
    [IDarray addObject:self.qgmode.ID];
    [self deleteItem:IDarray];
}
-(void)BottomBar:(BottomBar *)bottombar otherbtnClick:(NSInteger)index{
    NSLog(@"%ld",index);
    if (index==0&&self.dataarray.count>0) {
        [self showalert:0];
    }else{
        _candelete=NO;
        self.bottombar.btnenable=_candelete;
        self.bottombar.allselected=_candelete;
        [self.tableView.header beginRefreshing];
    }
}



-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tableView.header beginRefreshing];
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
    
    
}
-(NSMutableArray *)dataarray{
    if ( _dataarray==nil) {
        _dataarray=[NSMutableArray array];
    }
    return  _dataarray;
}
-(void)loadmore{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"my_buy_list";
    params[@"num"]=Kpagesize;
    NSInteger power=[self.user.power integerValue];
    if (power<5) {
        params[@"type"]=@"person";
        params[@"user_id"]=self.user.user_id;
    }else{
        params[@"type"]=@"company";
        params[@"user_id"]=self.user.com_id;
    }
    
    [PostUitls Post:myfindcarurl parameters:params success:^(id response) {
        
    } failure:^(NSError *error) {
        
    }];
    
        NSMutableArray *IDarray=[NSMutableArray array];
    for (FindCarMode *mode in self.dataarray) {
        [IDarray addObject:mode.ID];
    }
    
    params[@"page_id"]=[NSString DataTOjsonString:IDarray];
    
    [PostUitls Post:lookforcar parameters:params success:^(id response) {
        
        FindCarResdMode *mode=[FindCarResdMode modeWithDict:response];
        
        if ([mode.state integerValue]==400) {
            if (mode.data.count==6) {
                [self.tableView.footer resetNoMoreData];
            }else{
                [self.tableView.footer noticeNoMoreData];
            }
            
        }else{
            [self.tableView.footer noticeNoMoreData];
        }
        [self.dataarray addObjectsFromArray:mode.data];
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
        
        
    } failure:^(NSError *error) {
        [self.tableView.footer endRefreshing];
    }];
    
}
-(void)showalert:(NSInteger)tag{
    UIAlertView *alret=[[UIAlertView alloc]initWithTitle:@"提示" message:@"确认删除么?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alret.tag=tag;
    [alret show];
}
-(void)refresh{
    
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"my_buy_list";
    params[@"num"]=Kpagesize;
    NSInteger power=[self.user.power integerValue];
    if (power<5) {
        params[@"type"]=@"person";
        params[@"user_id"]=self.user.user_id;
    }else{
        params[@"type"]=@"company";
        params[@"user_id"]=self.user.com_id;
    }
    
    [PostUitls Post:myfindcarurl parameters:params success:^(id response) {
        [self.noitem hide];
        FindCarResdMode *mode=[FindCarResdMode modeWithDict:response];
        [self.dataarray removeAllObjects];
        if ([mode.state integerValue]==400) {
            if (mode.data.count==6) {
                [self.tableView.footer resetNoMoreData];
            }else{
                [self.tableView.footer noticeNoMoreData];
            }
            [self.dataarray addObjectsFromArray:mode.data];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        if (self.dataarray.count==0) {
            NSLog(@"没有上架的车源");
            [self.noitem show];
        }
        
    } failure:^(NSError *error) {
        [self.tableView.header endRefreshing];
    }];
    
    
}



-(void)rightclick{
    _isedting=!_isedting;
    [self setupRight:_isedting];
    [self.tableView reloadData];
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_isedting) {
        
        FindCarMode *mode=self.dataarray[indexPath.row];
        mode.ischecked=!mode.ischecked;
        FindCarTableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];
        cell.selectedbtn.selected=!cell.selectedbtn.selected;
        for (FindCarMode *mode in self.dataarray) {
            if (mode.ischecked) {
                _candelete=YES;
                break;
            }else{
                _candelete=mode.ischecked;
            }
        }
        self.bottombar.btnenable=_candelete;
        
    }else{
        FindCarMode *mode=self.dataarray[indexPath.row];
        LookForDetailController *vc=[LookForDetailController viewcontroller];
        vc.findmode=mode;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(void)setupRight:(BOOL)iseidting{
    if (iseidting) {
        UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
        [self.bottombar show];
        self.navigationItem.rightBarButtonItem=rightitem;
        
    }else{
        [self.bottombar hide];
        self.bottombar.allselected=NO;
        UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
        
        self.navigationItem.rightBarButtonItem=rightitem;
    }
    
    
}

-(NSInteger)numberofBottobarcount:(BottomBar *)bottombar{
    return self.dataarray.count;
}
-(BottomBar *)bottombar{
    if (_bottombar==nil) {
        _bottombar=[[BottomBar alloc]initWithBtnTitleArray:@[@"删除"] WithDelegate:self :YES];
        _bottombar.ishwopost=NO;
        _bottombar.datasource=self;
        [_bottombar addInView:self.view];
    }
    return _bottombar;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.dataarray.count;
}

-(void)BottomBarAllclick:(BottomBar *)bottombar{
    NSLog(@"all");
    for (FindCarMode *mode in self.dataarray) {
        mode.ischecked=bottombar.allselected;
    }
    [self.tableView reloadData];
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FindCarTableViewCell *cell=[FindCarTableViewCell CellWithTableView:tableView];
    cell.delegate=self;
    FindCarMode *mode=self.dataarray[indexPath.row];
    cell.mode=mode;
    cell.selectedbtn.hidden=!_isedting;
    return cell;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
